<?php


namespace App\Http\Controllers\Api;
use App\Http\Controllers\BaseController;
use App\Models\Balance;
use App\Models\Config;
use App\Models\CookbookAdvView;
use Illuminate\Http\Request;

class BalanceController extends BaseController
{
    /**
     * 列表
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request) {
        $merchant = $this->getUser();
        $start_at = $request->input('start_at');
        $end_at = $request->input('end_at');
        $type = $request->input('type');

        $list = Balance::withCertain('order.cookbook', ['title'])->where('parent_user_id', $merchant->id)
            ->startAt($start_at)->endAt($end_at)
            ->type($type)->orderBy("id", "desc")
            ->whereNotIn('type', [Balance::TYPE_WITHDRAW, Balance::TYPE_COOKBOOK, Balance::TYPE_COOKBOOK_REC])
            ->paginate(\request('per_page', 20));

        $max_date = Balance::where('parent_user_id', $merchant->id)->where('type', Balance::TYPE_COOKBOOK_VIDEO)->max('extra');
        $total = CookbookAdvView::where('merchant_id', $merchant->id)->where('benefit_user', 2)->when($max_date, function ($q) use($max_date){
            $q->where('month', '>', $max_date);
        })->where('is_finish', 1)->count();
        $total_adv_income = Config::getAdvUnit() * $total;

        return $this->paginate($list, [
            'total_adv_income' => $total_adv_income,
            'balance_yuan' => $merchant->balance_yuan ?: 0,
            'total_income_yuan' => format_yuan(Balance::getTotalIncome($merchant->id, 2))
        ]);
    }


}

